import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:sjx/pages/mine/mine_vm.dart';
import 'package:sjx/repository/model/task_status_number_model.dart';
import 'package:sjx/repository/model/user_info_model.dart';
import '../../route/route_utils.dart';
import '../../route/routes.dart';
import 'package:cached_network_image/cached_network_image.dart';

class MinePage extends StatefulWidget {
  const MinePage({super.key});

  @override
  _MinePageState createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  late final MineViewModel _viewModel;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _viewModel = MineViewModel();
    _fetchData();
  }

  Future<void> _fetchData() async {
    await _viewModel.requestUserInfo();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
        create: (context) {
      return _viewModel;
    },
      child: Consumer<MineViewModel>(builder: (context, value, child) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('个人主页'),
            actions: [
              IconButton(
                icon: const Icon(Icons.settings),
                onPressed: _goToSettings,
              ),
            ],
          ),
          body: _buildBody(context, value),
        );
      }),
    );
  }

  Widget _buildBody(BuildContext context, MineViewModel viewModel) {
    if (viewModel.isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (!viewModel.isLoggedIn) {
      return _buildNotLoggedInView(context);
    }

    return RefreshIndicator(
      onRefresh: _fetchData,
      child: SingleChildScrollView(
        controller: _scrollController,
        physics: const AlwaysScrollableScrollPhysics(),
        child: Column(
          children: [
            _buildUserInfo(viewModel.userInfoModel!),
            const SizedBox(height: 15),
            _buildBalanceSection(viewModel.userInfoModel!),
            const SizedBox(height: 15),
            _buildDoingTasks(viewModel.taskStatusNumberModel!),
            const SizedBox(height: 15),
            _buildPublishedTasks(viewModel.taskStatusNumberModel!),
            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }

  Widget _buildNotLoggedInView(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            'assets/images/error_login.png', // 替换为你的未登录图片
            width: 200.r,
            height: 200.r,
          ),
          const SizedBox(height: 20),
          const Text(
            '您还未登录，请先登录',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey,
            ),
          ),
          const SizedBox(height: 30),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: Theme.of(context).colorScheme.primary, // 按钮背景色
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
              ),
              padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 12),

            ),
            onPressed: () {
              // 跳转到登录页面
              RouteUtils.pushForNamed(context, RoutePath.login);
            },
            child: const Text(
              '立即登录',
              style: TextStyle(
                fontSize: 16,
                color: Colors.white,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildUserInfo(UserInfoModel model) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
      child: Row(
        children: [
          ClipOval(
            child: CachedNetworkImage(
              imageUrl: model.avatar,
              width: 60.r,
              height: 60.r,
              placeholder: (context, url) {
                return const Center(child: CircularProgressIndicator());
              },
              errorWidget: (context, url, error) {
                return Image.asset(
                  'assets/images/header.png',
                  width: 60.r,
                  height: 60.r,
                  fit: BoxFit.cover,
                );
              },
            ),
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      model.nickName,
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    )
                  ],
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    GestureDetector(
                      onTap: _goToFollowing,
                      child: RichText(
                        text: TextSpan(
                          text: '${model.attentionCount}关注 ',
                          style: const TextStyle(
                            fontSize: 15,
                            color: Colors.black,
                          ),
                          children: const [
                            TextSpan(
                              text: ' ',
                              style: TextStyle(color: Colors.grey),
                            ),
                          ],
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: _goToFollowers,
                      child: RichText(
                        text: TextSpan(
                          text: '${model.fansCount}粉丝',
                          style: const TextStyle(
                            fontSize: 15,
                            color: Colors.black,
                          ),
                          children: const [
                            TextSpan(
                              text: ' ',
                              style: TextStyle(color: Colors.grey),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBalanceSection(UserInfoModel model) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 15),
      child: Row(
        children: [
          Expanded(
            child: _buildBalanceCard(
              title: '账户余额(元)',
              amount: model.balanceAmount.toStringAsFixed(2),
              leftButtonText: '提现',
              rightButtonText: '明细',
              leftButtonOnPressed: _goToWithdraw,
              rightButtonOnPressed: _goToCashRecord,
              imageName: "wode_zhanghu_bg.png",
            ),
          ),
          const SizedBox(width: 15),
          Expanded(
            child: _buildBalanceCard(
              title: '金币数(个)',
              amount: model.balanceCoinAmount.toString(),
              leftButtonText: '出售',
              rightButtonText: '明细',
              leftButtonOnPressed: _goToSellCoin,
              rightButtonOnPressed: _goToCoinRecord,
              imageName: "wode_jinbi_bg.png",
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBalanceCard({
    required String title,
    required String amount,
    required String leftButtonText,
    required String rightButtonText,
    required VoidCallback leftButtonOnPressed,
    required VoidCallback rightButtonOnPressed,
    required String imageName,
  }) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Color.fromRGBO(200, 200, 200, 0.1),
            spreadRadius: 2,
            blurRadius: 5,
            offset: Offset(0, 2),
          )
        ]
      ),
      child: Card(
        elevation: 0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 10),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            image: DecorationImage(
              image: AssetImage('assets/images/$imageName'), // 使用图片作为背景
              fit: BoxFit.cover,
            ),
          ),
          child: Column(
            children: [
              Text(
                title,
                style: const TextStyle(
                  fontSize: 13,
                  color: Colors.white,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                amount,
                style: const TextStyle(
                  fontSize: 21,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              const SizedBox(height: 8),
              Container(
                height: 35,
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.4),
                ),
                child: Row(
                  children: [
                    Expanded(
                      child: TextButton(
                        onPressed: leftButtonOnPressed,
                        child: Text(
                          leftButtonText,
                          style: TextStyle(
                            fontSize: 13,
                            color: Color.fromRGBO(178, 134, 84, 1.0),
                          ),
                        ),
                      ),
                    ),
                    Container(
                      width: 1,
                      height: 17,
                      color: Colors.white.withOpacity(0.7),
                    ),
                    Expanded(
                      child: TextButton(
                        onPressed: rightButtonOnPressed,
                        child: Text(
                          rightButtonText,
                          style: TextStyle(
                            fontSize: 13,
                            color: Color.fromRGBO(178, 134, 84, 1.0),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildDoingTasks(TaskStatusNumberModel _taskNumber) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 15),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            boxShadow: [
              BoxShadow(
                color: Color.fromRGBO(200, 200, 200, 0.2),
                spreadRadius: 2,
                blurRadius: 5,
                offset: Offset(0, 2),
              )
            ]
        ),
      child: Card(
        elevation: 0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        child: Padding(
          padding: const EdgeInsets.all(15),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                '我在做的任务',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 15),
              GridView.count(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                crossAxisCount: 3,
                childAspectRatio: 1.5,
                children: [
                  _buildTaskItem(
                    imageName: "wode_daitijiao_icon.png",
                    title: '待提交(${_taskNumber.myOrderReadyToSubmitOrderCount})',
                    onPressed: () => _goToTaskDoing(1),
                  ),
                  _buildTaskItem(
                    imageName: "wode_daishenhe_icon.png",
                    title: '待审核(${_taskNumber.myOrderReadyToApproveCount})',
                    onPressed: () => _goToTaskDoing(2),
                  ),
                  _buildTaskItem(
                    imageName: "wode_wetongguo_icon.png",
                    title: '已拒绝(${_taskNumber.myOrderRejectCount})',
                    onPressed: () => _goToTaskDoing(3),
                  ),
                  _buildTaskItem(
                    imageName: "wode_yihuoshang_icon.png",
                    title: '已获赏(${_taskNumber.myOrderGotMoneyCount})',
                    onPressed: () => _goToTaskDoing(4),
                  ),
                  _buildTaskItem(
                    imageName: "wode_shibai_icon.png",
                    title: '任务失败(${_taskNumber.myOrderFailedCount})',
                    onPressed: () => _goToTaskDoing(5),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildPublishedTasks(TaskStatusNumberModel _taskNumber) {
    return Container(
        margin: const EdgeInsets.symmetric(horizontal: 15),
    decoration: BoxDecoration(
    borderRadius: BorderRadius.circular(8),
    boxShadow: [
    BoxShadow(
    color: Color.fromRGBO(200, 200, 200, 0.2),
    spreadRadius: 2,
    blurRadius: 5,
    offset: Offset(0, 2),
    )
    ]
    ),
    child: Card(
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: Padding(
        padding: const EdgeInsets.all(15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '我发布的任务',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                GestureDetector(
                  onTap: _goToPublishTask, // 添加点击事件
                  child: const Text(
                    '创建任务',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue, // 添加颜色以表明可点击
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 15),
            GridView.count(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              crossAxisCount: 3,
              childAspectRatio: 1.5,
              children: [
                _buildTaskItem(
                  imageName: "wode_shenhezhong_icon.png",
                  title: '审核中(${_taskNumber.taskReadyToSubmitOrderCount})',
                  onPressed: () => _goToTaskPublished(0),
                ),
                _buildTaskItem(
                  imageName: "wode_daifukuan_icon.png",
                  title: '待付款(${_taskNumber.taskReadyToPayCount})',
                  onPressed: () => _goToTaskPublished(1),
                ),
                _buildTaskItem(
                  imageName: "wode_jinxingzhong_icon.png",
                  title: '进行中(${_taskNumber.taskInprocessCount})',
                  onPressed: () => _goToTaskPublished(2),
                ),
                _buildTaskItem(
                  imageName: "wode_daijieshu_icon.png",
                  title: '等待结束(${_taskNumber.taskWaitToEndCount})',
                  onPressed: () => _goToTaskPublished(3),
                ),
                _buildTaskItem(
                  imageName: "wode_yijieshu_icon.png",
                  title: '已结束(${_taskNumber.taskCompleteCount})',
                  onPressed: () => _goToTaskPublished(4),
                ),
                _buildTaskItem(
                  imageName: "wode_yijujue_icon.png",
                  title: '审核失败(${_taskNumber.taskRejectCount})',
                  onPressed: () => _goToTaskPublished(5),
                ),
              ],
            ),
          ],
        ),
      ),
    ),
    );
  }

  Widget _buildTaskItem({
    required String imageName,
    required String title,
    required VoidCallback onPressed,
  }) {
    return TextButton(
      onPressed: onPressed,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            'assets/images/$imageName',
            width: 46.r,
            height: 33.r,
          ),
          const SizedBox(height: 5),
          Text(
            title,
            textAlign: TextAlign.center,
            style: const TextStyle(
              fontSize: 13,
              color: Colors.black,
            ),
          ),
        ],
      ),
    );
  }

  // 导航方法
  void _goToFollowing() {
    // 跳转到关注页面
  }

  void _goToFollowers() {
    // 跳转到粉丝页面
  }

  void _goToSettings() {
    // 跳转到设置页面
    RouteUtils.pushForNamed(context, RoutePath.setting);
  }

  void _goToWithdraw() {
    // 跳转到提现页面
    RouteUtils.pushForNamed(context, RoutePath.withdrawal);
  }

  void _goToCashRecord() {
    // 跳转到现金明细页面
    RouteUtils.pushForNamed(context, RoutePath.transaction_record_cash);
  }

  void _goToSellCoin() {
    // 跳转到出售金币页面
    RouteUtils.pushForNamed(context, RoutePath.sale_coin);
  }

  void _goToCoinRecord() {
    // 跳转到金币明细页面
    RouteUtils.pushForNamed(context, RoutePath.transaction_record_coin);

  }

  void _goToPublishTask() {
    // 跳转到发布任务页面
    RouteUtils.pushForNamed(context, RoutePath.task_create_choose_type);
  }

  void _goToTaskDoing(int index) {
    // 跳转到任务管理页面
    RouteUtils.pushForNamed(
        context,
        RoutePath.task_receive_list,
        arguments: {
          'taskStatusNumber': _viewModel.taskStatusNumberModel,
          'index': index
        }
    );
  }

  void _goToTaskPublished(int index) {
    // 跳转到发布任务管理页面
    RouteUtils.pushForNamed(
        context,
        RoutePath.task_publish_list,
        arguments: {
          'taskStatusNumber': _viewModel.taskStatusNumberModel,
          'index': index
        }
    );
  }
}